//
//  UITextField+Tool.m
//  SLDemo
//
//  Created by bocai on 2016/12/20.
//  Copyright © 2016年 Heracles. All rights reserved.
//

#import "UITextField+Tool.h"
#import <objc/runtime.h>

static NSString *const kWordLimitKey = @"kWordLimitKey";
static NSString *const kDecimalLimitKey = @"kDecimalLimitKey";
static NSString *const kPlaceholderColorKey = @"_placeholderLabel.textColor";

@implementation UITextField (Tool)

- (UIColor *)t_placeholderColor
{
    return [self valueForKeyPath:kPlaceholderColorKey];
}

- (void)setT_placeholderColor:(UIColor *)t_placeholderColor
{
    [self setValue:t_placeholderColor forKeyPath:kPlaceholderColorKey];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(t_limitTextFieldWord) name:UITextFieldTextDidChangeNotification object:nil];
}

- (NSInteger)t_wordLimit
{
    return [objc_getAssociatedObject(self, (__bridge const void *)(kWordLimitKey)) integerValue];
}

- (void)setT_wordLimit:(NSInteger)t_wordLimit
{
    objc_setAssociatedObject(self, (__bridge const void *)(kWordLimitKey), @(t_wordLimit), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(t_limitTextFieldDecimal) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)t_limitTextFieldWord
{
    if (!self.markedTextRange && self.text.length > self.t_wordLimit) {
        self.text = [self.text substringToIndex:self.t_wordLimit];
    }
}

- (NSInteger)t_decimalLimit
{
    return [objc_getAssociatedObject(self, (__bridge const void *)(kDecimalLimitKey)) integerValue];
}

- (void)setT_decimalLimit:(NSInteger)t_decimalLimit
{
    objc_setAssociatedObject(self, (__bridge const void *)(kDecimalLimitKey), @(t_decimalLimit), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)t_limitTextFieldDecimal
{
    NSArray *array = [self.text componentsSeparatedByString:@"."];
    if (array.count > 2 || (array.count == 2 && [array.lastObject length] > self.t_decimalLimit)) {
//        self.text = [self.text ]<##>
    }
}

@end
